<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>StatiCrypt: Password protect static HTML</title>
        <meta name="description" content="" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link
            rel="stylesheet"
            type="text/css"
            href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
            integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
            crossorigin="anonymous"
        />
        <style>
            a.no-style {
                color: inherit;
                text-decoration: inherit;
            }

            body {
                font-size: 16px;
            }

            label.no-style {
                font-weight: normal;
            }

            @media screen and (-webkit-min-device-pixel-ratio: 0) {
                .staticrypt-form input[type="password"],
                input[type="text"] {
                    font-size: 16px;
                }
            }

            .footer {
                width: 100%;
                background-color: #f8f9fa;
                padding: 20px;
                text-align: center;
                margin-top: 10em;
            }
        </style>

        <!-- point to my other project as the canonical in the eyes of google - the two projects are kept in sync, and people can still use the github page hosted one for maximum transparency -->
        <link rel="canonical" href="https://translateabook.com/staticrypt/" />
    </head>

    <body>
        <div class="container">
            <div class="row">
                <div class="col-xs-12">
                    <h1>
                        StatiCrypt
                        <div class="pull-right">
                            <iframe
                                src="https://ghbtns.com/github-btn.html?user=robinmoisson&repo=staticrypt&type=star&size=large"
                                frameborder="0"
                                scrolling="0"
                                width="80px"
                                height="30px"
                            ></iframe>
                            <iframe
                                src="https://ghbtns.com/github-btn.html?user=robinmoisson&repo=staticrypt&type=fork&size=large"
                                frameborder="0"
                                scrolling="0"
                                width="80px"
                                height="30px"
                            ></iframe>
                        </div>
                        <br />
                        <small>Password protect a static HTML page</small>
                    </h1>
                    <p>
                        StatiCrypt uses AES-256 with WebCrypto to encrypt your html string with your long password, in
                        your browser (client side).
                    </p>
                    <p>
                        Download your encrypted string in a HTML page with a password prompt you can upload anywhere
                        (see <a target="_blank" href="example/encrypted/example.html">example</a>).
                    </p>
                    <p>
                        The tool is also available as
                        <a href="https://npmjs.com/package/staticrypt">a CLI on NPM</a> and is
                        <a href="https://github.com/robinmoisson/staticrypt">open source on GitHub</a>.
                    </p>
                    <br />

                    <h4>
                        <a class="no-style" id="toggle-concept" href="#">
                            <span id="toggle-concept-sign">►</span> HOW IT WORKS
                        </a>
                    </h4>
                    <div id="concept" class="hidden">
                        <p>
                            <b class="text-danger">Disclaimer</b> if you are an at-risk activist, or have extra
                            sensitive banking data, you should probably use something else!
                        </p>
                        <p>
                            StatiCrypt generates a static, password protected page that can be decrypted in-browser:
                            just send or upload the generated page to a place serving static content (github pages, for
                            example) and you're done: the javascript will prompt users for password, decrypt the page
                            and load your HTML.
                        </p>
                        <p>
                            The page is encrypted with AES-256 in CBC mode (see why this mode is appropriate for
                            StatiCrypt in
                            <a href="https://github.com/robinmoisson/staticrypt/issues/19">#19</a>). The password is
                            hashed with PBKDF2 (599k iterations with SHA-256, plus 1k with SHA-1 for legacy reasons (see
                            <a href="https://github.com/robinmoisson/staticrypt/issues/159">#159</a>), for the added
                            <a
                                href="https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2"
                                >recommended total</a
                            >
                            of 600k) and used to encrypt the page.
                        </p>
                        <p>
                            It basically encrypts your page and puts everything with a user-friendly way to use a
                            password in the new file. AES-256 is state of the art but
                            <b
                                >brute-force/dictionary attacks would be easy to do at a really fast pace: use a long,
                                unusual password!</b
                            >
                            <br />
                            => To be safe, we recommend 16+ alphanum characters, and using a password manager like the
                            open-source <a href="http://bitwarden.com">Bitwarden</a>.
                        </p>
                        <p>
                            Feel free to contribute or report any thought to the
                            <a href="https://github.com/robinmoisson/staticrypt">GitHub project</a>.
                        </p>
                    </div>
                    <br />
                </div>
            </div>
            <div class="row">
                <div class="col-xs-12">
                    <form id="encrypt_form">
                        <div class="form-group">
                            <label for="password">Password</label>
                            <input
                                type="password"
                                class="form-control"
                                id="password"
                                placeholder="Password (choose a long one!)"
                            />
                        </div>

                        <div class="form-group">
                            <label for="unencrypted_html">HTML/string to encrypt</label>
                            <textarea
                                class="form-control"
                                id="unencrypted_html"
                                placeholder="<html><head>..."
                                rows="5"
                            ></textarea>
                        </div>

                        <div class="form-group">
                            <label class="no-style">
                                <input type="checkbox" id="remember" checked />
                                Add "Remember me" checkbox (append <code>#staticrypt_logout</code> to your URL to
                                logout)
                                <small>
                                    <abbr
                                        class="text-muted"
                                        title='The password will be stored in clear text in the browser&apos;s localStorage upon entry by the user. See "More options" to set the expiration (default: none)'
                                    >
                                        (?)
                                    </abbr>
                                </small>
                            </label>
                        </div>

                        <p>
                            <a href="#" id="toggle-extra-option">+ More options</a>
                        </p>
                        <div id="extra-options" class="hidden">
                            <div class="form-group">
                                <label for="template_title">Page title</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    id="template_title"
                                    placeholder="Default: 'Protected Page'"
                                />
                            </div>

                            <div class="form-group">
                                <label for="template_instructions">Instructions to display the user</label>
                                <textarea
                                    class="form-control"
                                    id="template_instructions"
                                    placeholder="Default: nothing."
                                ></textarea>
                            </div>

                            <div class="form-group">
                                <label for="template_placeholder">Password input placeholder</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    id="template_placeholder"
                                    placeholder="Default: 'Password'"
                                />
                            </div>

                            <div class="form-group">
                                <label for="template_remember">"Remember me" checkbox label</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    id="template_remember"
                                    placeholder="Default: 'Remember me'"
                                />
                            </div>

                            <div class="form-group">
                                <label for="remember_in_days">"Remember me" expiration in days</label>
                                <input
                                    type="number"
                                    class="form-control"
                                    id="remember_in_days"
                                    step="any"
                                    placeholder="Default: 0 (no expiration)"
                                />
                                <small class="form-text text-muted">
                                    After this many days, the user will have to enter the password again. Leave empty or
                                    set to 0 for no expiration.
                                </small>
                            </div>

                            <div class="form-group">
                                <label for="template_button">Decrypt button label</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    id="template_button"
                                    placeholder="Default: 'DECRYPT'"
                                />
                            </div>

                            <div class="form-group">
                                <label for="template_color_primary">Primary color (button, ...)</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    id="template_color_primary"
                                    placeholder="Default: '#4CAF50'"
                                />
                            </div>

                            <div class="form-group">
                                <label for="template_color_secondary">Secondary color (background, ...)</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    id="template_color_secondary"
                                    placeholder="Default: '#76B852'"
                                />
                            </div>
                        </div>

                        <button class="btn btn-primary pull-right" type="submit">
                            Generate password protected HTML
                        </button>
                    </form>
                </div>
            </div>

            <div class="row mb-5">
                <div class="col-xs-12">
                    <h2>Encrypted HTML</h2>
                    <p>
                        <a
                            class="btn btn-success download"
                            download="encrypted.html"
                            id="download-link"
                            disabled="disabled"
                            >Download html file with password prompt</a
                        >
                    </p>
                    <pre id="encrypted_html_display">Your encrypted string</pre>
                </div>
            </div>
        </div>

        <div class="footer">
            Thank you for using StatiCrypt - I hope you like the tool!
            <br />
            If you'd like to support it you can
            <a href="https://github.com/sponsors/robinmoisson" target="_blank">sponsor me on github</a>, or check-out my
            other project to <a href="https://translateabook.com" target="_blank">Translate a Book</a> with LLMs.
        </div>

        <script id="cryptoEngine">
            window.cryptoEngine = /*[|js_crypto_engine|]*/ 0;
        </script>

        <script id="codec">
            window.codec = /*[|js_codec|]*/ 0;
        </script>

        <script id="formater">
            window.formater = /*[|js_formater|]*/ 0;
        </script>

        <script id="staticrypt">
            window.staticrypt = /*[|js_staticrypt|]*/ 0;
        </script>

        <script>
            const encode = codec.init(cryptoEngine).encode;

            let htmlToDownload;

            /**
             * Extract js code from <script> tag and return it as a string
             *
             * @param {string} id
             * @returns {string}
             */
            function getScriptAsString(id) {
                return document.getElementById(id).innerText.replace(/window\.\w+ = /, "");
            }

            /**
             * Register something happened - this uses a simple Supabase function to implement a counter, and allows to drop
             * google analytics. We don't store any personal data or IP.
             *
             * @param {string} action
             */
            function trackEvent(action) {
                const xhr = new XMLHttpRequest();
                xhr.open("POST", "https://zlgpaemmniviswibzuwt.supabase.co/rest/v1/rpc/increment_analytics", true);
                xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
                xhr.setRequestHeader(
                    "apikey",
                    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InpsZ3BhZW1tbml2aXN3aWJ6dXd0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2NjkxMjM0OTcsImV4cCI6MTk4NDY5OTQ5N30.wNoVDHG7F6INx-IPotMs3fL1nudfaF2qvQDgG-1PhNI"
                );
                xhr.setRequestHeader(
                    "Authorization",
                    "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InpsZ3BhZW1tbml2aXN3aWJ6dXd0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2NjkxMjM0OTcsImV4cCI6MTk4NDY5OTQ5N30.wNoVDHG7F6INx-IPotMs3fL1nudfaF2qvQDgG-1PhNI"
                );
                xhr.send(
                    JSON.stringify({
                        action_input: action,
                    })
                );
            }

            /**
             * Fill the password prompt template with data provided.
             * @param data
             */
            function setFileToDownload(data) {
                const request = new XMLHttpRequest();
                request.open("GET", "lib/password_template.html", true);
                request.onload = function () {
                    const renderedTmpl = formater.renderTemplate(request.responseText, data);

                    const downloadLink = document.querySelector("a.download");
                    downloadLink.href = "data:text/html," + encodeURIComponent(renderedTmpl);
                    downloadLink.removeAttribute("disabled");

                    htmlToDownload = renderedTmpl;
                };
                request.send();
            }

            // register page load
            window.onload = function () {
                trackEvent("show_index");
            };

            /**
             * Handle form submission.
             */
            document.getElementById("encrypt_form").addEventListener("submit", async function (e) {
                e.preventDefault();

                trackEvent("generate_encrypted");

                const unencrypted = document.getElementById("unencrypted_html").value,
                    password = document.getElementById("password").value;

                const salt = cryptoEngine.generateRandomSalt();
                const encryptedMsg = await encode(unencrypted, password, salt);

                const templateButton = document.getElementById("template_button").value,
                    templateColorPrimary = document.getElementById("template_color_primary").value,
                    templateColorSecondary = document.getElementById("template_color_secondary").value,
                    templateInstructions = document.getElementById("template_instructions").value,
                    isRememberEnabled = document.getElementById("remember").checked,
                    templateTitle = document.getElementById("template_title").value.trim(),
                    templatePlaceholder = document.getElementById("template_placeholder").value.trim(),
                    rememberDurationInDays = document.getElementById("remember_in_days").value || 0,
                    templateRemember = document.getElementById("template_remember").value;

                const data = {
                    staticrypt_config: {
                        staticryptEncryptedMsgUniqueVariableName: encryptedMsg,
                        isRememberEnabled,
                        rememberDurationInDays,
                        staticryptSaltUniqueVariableName: salt,
                    },
                    is_remember_enabled: JSON.stringify(isRememberEnabled),
                    js_staticrypt: getScriptAsString("staticrypt"),
                    template_button: templateButton ? templateButton : "DECRYPT",
                    template_color_primary: templateColorPrimary || "#4CAF50",
                    template_color_secondary: templateColorSecondary || "#76B852",
                    template_instructions: templateInstructions || "",
                    template_placeholder: templatePlaceholder || "Password",
                    template_remember: templateRemember || "Remember me",
                    template_title: templateTitle || "Protected Page",
                };

                document.getElementById("encrypted_html_display").textContent = encryptedMsg;

                setFileToDownload(data);
            });

            document.getElementById("toggle-extra-option").addEventListener("click", function (e) {
                e.preventDefault();
                document.getElementById("extra-options").classList.toggle("hidden");
            });

            let isConceptShown = false;
            document.getElementById("toggle-concept").addEventListener("click", function (e) {
                e.preventDefault();

                isConceptShown = !isConceptShown;

                document.getElementById("toggle-concept-sign").innerText = isConceptShown ? "▼" : "►";

                document.getElementById("concept").classList.toggle("hidden");
            });

            /**
             * Browser specific download code.
             */
            document.getElementById("download-link").addEventListener("click", function (e) {
                // only register the click event if there is actually a generated file
                if (htmlToDownload) {
                    trackEvent("download_encrypted");
                }

                const isIE = navigator.userAgent.indexOf("MSIE") !== -1 || !!document.documentMode === true; // >= 10
                const isEdge = navigator.userAgent.indexOf("Edge") !== -1;

                // download with MS specific feature
                if (htmlToDownload && (isIE || isEdge)) {
                    e.preventDefault();
                    const blobObject = new Blob([htmlToDownload]);
                    window.navigator.msSaveOrOpenBlob(blobObject, "encrypted.html");
                }

                return true;
            });
        </script>
    </body>
</html>
